﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace SecurityDev
{
    public partial class InitializeObject : Form
    {
        decimal object_seq;
        OpenFileDialog openFileDialog1;

        void InitializeConstructor()
        {
            InitializeComponent();

            openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Image Files |*.jpg;*.jpeg;*.bmp;*.png|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.Multiselect = true;

            string fileStr = "Categories";
            if (System.IO.File.Exists(fileStr))
            {
                CategoryComboBox.DataSource = System.IO.File.ReadAllLines(fileStr);
            }
            CategoryComboBox.SelectedIndex = -1;

            string fileStr1 = "Regions";
            if (System.IO.File.Exists(fileStr1))
            {
                regionComboBox.DataSource = System.IO.File.ReadAllLines(fileStr1);
            }
            regionComboBox.SelectedIndex = -1;
        }

        public InitializeObject()//add object
        {
            InitializeConstructor();

            this.Text = "Add object";
            addChangeObjectBtn.Text = "Add object";
            addChangeObjectBtn.Click += new System.EventHandler(AddObjectBtn_Click);

            var personsStr = from p in DS.outpost.person
                             select string.Format("Id: {0}; Name: {1} {2}", p.person_seq.ToString(), p.person_name, p.person_lastname);

            foreach (var item in personsStr)
            {
                personCheckedListBox.Items.Add((object)item);
            }
        }

        public InitializeObject(decimal obj_seq)//change object
        {
            InitializeConstructor();

            this.Text = "Change object id: " + obj_seq;
            addChangeObjectBtn.Text = "Change object";
            addChangeObjectBtn.Click += new System.EventHandler(ChangeObjectBtn_Click);
            object_seq = obj_seq;

            OutpostDS.objectRow change_objRow = DS.outpost._object.FindByobj_seq(obj_seq);

            objectName.Text = change_objRow.obj_name;
            addressTextBox.Text = change_objRow.obj_adress;
            priorityComboBox.SelectedIndex = priorityComboBox.FindString(change_objRow.obj_priority.ToString());
            phoneBox.Text = change_objRow.obj_phone;
            photoTextBox.Text = change_objRow.obj_photo_url;
            CategoryComboBox.SelectedIndex = change_objRow.obj_category == "" ? -1 : CategoryComboBox.FindString(change_objRow.obj_category);
            regionComboBox.SelectedIndex = change_objRow.obj_region == "" ? -1 : regionComboBox.FindString(change_objRow.obj_region);
            linkLabel1.Text = change_objRow.obj_coord;
            pathTextBox.Text = change_objRow.obj_path;
            schemaTextBox.Text = change_objRow.obj_schema;

            decimal[] perSeqsIn_ObjPer = (from op in DS.outpost.object_person
                                          where op.obj_seq == object_seq
                                          select op.person_seq).ToArray();

            foreach (var person in DS.outpost.person)
            {
                if (CheckPersonSeqInObjPer(person, perSeqsIn_ObjPer))
                {
                    personCheckedListBox.Items.Add((object)string.Format(
                        "Id: {0}; Name: {1} {2}", person.person_seq.ToString(), person.person_name, person.person_lastname), true);
                }
                else
                {
                    personCheckedListBox.Items.Add((object)string.Format(
                        "Id: {0}; Name: {1} {2}", person.person_seq.ToString(), person.person_name, person.person_lastname));
                }
            }
        }

        bool CheckPersonSeqInObjPer(OutpostDS.personRow persR, decimal[] pers_seqs)
        {
            foreach (var pers_seq in pers_seqs)
            {
                if (pers_seq == persR.person_seq)
                {
                    return true;
                }
            }
            return false;
        }


        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string[] str = linkLabel1.Text.Split(',');
            if (str.Count() == 2 && str[0] != "" && str[1] != "")
            {
                ProcessStartInfo sInfo = new ProcessStartInfo("http://maps.google.com/?q=" + linkLabel1.Text);
                Process.Start(sInfo);
            }
        }

        private void ChooseFromMapBtn_Click(object sender, EventArgs e)
        {
            Gmap gmap = new Gmap();
            gmap.MapUpdated += new Gmap.MapUpdateHandler(resetText);
            gmap.Show();
        }

        private void resetText(object sender, MapUpdateEventArgs e)
        {
            linkLabel1.Text = e.getLat.Replace(',', '.') + ", " + e.getLng.Replace(',', '.');
        }

        private void Photo_Btn_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                photoTextBox.Text += string.Join(";", openFileDialog1.FileNames);
                if (openFileDialog1.FileNames.Count() == 1)
                {
                    photoTextBox.Text += ";";
                }
            }
        }

        private void pathBtn_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                pathTextBox.Text += string.Join(";", openFileDialog1.FileNames);
                if (openFileDialog1.FileNames.Count() == 1)
                {
                    pathTextBox.Text += ";";
                }
            }
        }

        private void schemaBtn_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                schemaTextBox.Text += string.Join(";", openFileDialog1.FileNames);
                if (openFileDialog1.FileNames.Count() == 1)
                {
                    schemaTextBox.Text += ";";
                }
            }
        }

        private void AddObjectBtn_Click(object sender, EventArgs e)
        {
            if (!CheckText.IsValidPhone(phoneBox.Text))
            {
                MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (objectName.Text == "" || addressTextBox.Text == "" ||
                priorityComboBox.SelectedIndex == -1 || CategoryComboBox.SelectedIndex == -1 ||
                regionComboBox.SelectedIndex == -1 || linkLabel1.Text == "" ||
                photoTextBox.Text == "" || pathTextBox.Text == "" || schemaTextBox.Text == "")
            {
                if (MessageBox.Show("Some fields aren't filled. Do you want to continue?",
                    "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==
                    System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            var last_obj_seq = (from o in DS.outpost._object
                                orderby o.obj_seq ascending
                                select o.obj_seq).LastOrDefault();

            OutpostDS.objectRow new_objrow = DS.outpost._object.NewobjectRow();

            new_objrow.obj_seq = ++last_obj_seq;
            new_objrow.obj_name = objectName.Text;
            new_objrow.obj_adress = addressTextBox.Text;
            new_objrow.obj_priority = priorityComboBox.SelectedIndex == -1 ? 0 : (Convert.ToDecimal(priorityComboBox.SelectedItem));
            new_objrow.obj_category = CategoryComboBox.SelectedIndex == -1 ? "" : (string)CategoryComboBox.SelectedItem;
            new_objrow.obj_region = regionComboBox.SelectedIndex == -1 ? "" : (string)regionComboBox.SelectedItem;
            new_objrow.obj_phone = phoneBox.Text;
            new_objrow.obj_photo_url = photoTextBox.Text;
            new_objrow.obj_coord = linkLabel1.Text;
            new_objrow.obj_path = pathTextBox.Text;
            new_objrow.obj_schema = schemaTextBox.Text;

            DS.outpost._object.AddobjectRow(new_objrow);

            decimal op_seq = (from op in DS.outpost.object_person
                              orderby op.seq ascending
                              select op.seq).LastOrDefault();


            decimal person_seq;
            for (int i = 0; i < personCheckedListBox.CheckedItems.Count; i++)
            {
                person_seq = Convert.ToDecimal(((string)personCheckedListBox.CheckedItems[i]).Substring(4, ((string)personCheckedListBox.CheckedItems[i]).IndexOf(';') - 4));
                DS.outpost.object_person.Addobject_personRow(++op_seq, DS.outpost.person.FindByperson_seq(person_seq), DS.outpost._object.FindByobj_seq(new_objrow.obj_seq));
            }

            try
            {
                DS.objetcAdapter.Update(DS.outpost._object);
                DS.object_personAdapter.Update(DS.outpost.object_person);

            }
            catch (Exception xException)
            {
                MessageBox.Show(xException.Message);
            }
            Close();
        }

        private void ChangeObjectBtn_Click(object sender, EventArgs e)
        {
            if (!CheckText.IsValidPhone(phoneBox.Text))
            {
                MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (objectName.Text == "" || addressTextBox.Text == "" ||
                priorityComboBox.SelectedIndex == -1 || CategoryComboBox.SelectedIndex == -1 ||
                regionComboBox.SelectedIndex == -1 || linkLabel1.Text == "" ||
                photoTextBox.Text == "" || pathTextBox.Text == "" || schemaTextBox.Text == "")
            {
                if (MessageBox.Show("Some fields aren't filled. Do you want to continue?",
                    "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==
                    System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            OutpostDS.objectRow changeObj = DS.outpost._object.FindByobj_seq(object_seq);


            changeObj.obj_name = objectName.Text;
            changeObj.obj_adress = addressTextBox.Text;
            changeObj.obj_phone = phoneBox.Text;
            changeObj.obj_priority = priorityComboBox.SelectedIndex == -1 ? 0 : (Convert.ToDecimal(priorityComboBox.SelectedItem));
            changeObj.obj_category = CategoryComboBox.SelectedIndex == -1 ? "" : (string)CategoryComboBox.SelectedItem;
            changeObj.obj_region = regionComboBox.SelectedIndex == -1 ? "" : (string)regionComboBox.SelectedItem;
            changeObj.obj_coord = linkLabel1.Text;
            changeObj.obj_photo_url = photoTextBox.Text;
            changeObj.obj_schema = schemaTextBox.Text;
            changeObj.obj_path = pathTextBox.Text;

            var op_seq = (from op in DS.outpost.object_person
                          orderby op.seq ascending
                          select op.seq).LastOrDefault();


            decimal person_seq;
            for (int i = 0; i < personCheckedListBox.Items.Count; i++)
            {
                person_seq = Convert.ToDecimal(((string)personCheckedListBox.Items[i]).Substring(4, ((string)personCheckedListBox.Items[i]).IndexOf(';') - 4));
                OutpostDS.object_personRow opR = DS.outpost.object_person.FirstOrDefault((op) =>
                    {
                        if (op.obj_seq == changeObj.obj_seq && op.person_seq == person_seq)
                        {
                            return true;
                        }
                        return false;
                    });

                if (opR != null)
                {
                    switch (personCheckedListBox.GetItemChecked(i))
                    {
                        case true:
                            break;
                        case false:
                            opR.Delete();
                            break;
                        default:
                            break;
                    }
                }
                else//opR == null
                {
                    switch (personCheckedListBox.GetItemChecked(i))
                    {
                        case true:
                            DS.outpost.object_person.Addobject_personRow(++op_seq, DS.outpost.person.FindByperson_seq(person_seq), DS.outpost._object.FindByobj_seq(changeObj.obj_seq));
                            break;
                        case false:
                            break;
                        default:
                            break;
                    }
                }
            }

            try
            {
                DS.objetcAdapter.Update(DS.outpost._object);
                DS.object_personAdapter.Update(DS.outpost.object_person);
            }
            catch (NullReferenceException xException)
            {
                MessageBox.Show(xException.Message);
            }
            Close();
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void categoryBtn_Click(object sender, EventArgs e)
        {
            CategoriesForm category = new CategoriesForm();
            category.ShowDialog();

            string fileStr = "Categories";
            if (System.IO.File.Exists(fileStr))
            {
                CategoryComboBox.DataSource = System.IO.File.ReadAllLines(fileStr);
            }
            CategoryComboBox.SelectedIndex = -1;
        }

        private void regionBtn_Click(object sender, EventArgs e)
        {
            RegionsForm region = new RegionsForm();
            region.ShowDialog();

            string fileStr1 = "Regions";
            if (System.IO.File.Exists(fileStr1))
            {
                regionComboBox.DataSource = System.IO.File.ReadAllLines(fileStr1);
            }
            regionComboBox.SelectedIndex = -1;
        }


    }
}